# -*- coding: utf-8 -*-

import json
import requests
import time
import socket
from log import set_log

logger = set_log('debug', 'db.log')


class Falcon:
    '''
        During Instantiation, you must pass two keyword-arguments: metric and value. If you do not
        pass 'endpoint' parameter. endpoint will equal socket.gethostname()
        Default：
        tags --> empty string
        step --> 60
        counterType --> GAUGE
        endpoint --> socket.gethostname()
    '''
    def __init__(self, **kwargs):
        self.metric = kwargs['metric']
        self.value = kwargs['value']
        self._agt_api = u'http://127.0.0.1:1988/v1/push'
        self.step = 'step' in kwargs and kwargs['step'] or 60
        self.tags = 'tags' in kwargs and kwargs['tags'] or str()
        self.counterType = 'counterType' in kwargs and kwargs['counterType'] or 'GAUGE'
        self.endpoint = 'endpoint' in kwargs and kwargs['endpoint'] or socket.gethostname()

    def _data_serial(self):
        payload = [
            {
                "endpoint": self.endpoint,
                "metric": self.metric,
                "timestamp": int(time.time()),
                "step": self.step,
                "value": self.value,
                "counterType": self.counterType,
                "tags": self.tags,
            },
        ]
        return json.dumps(payload)

    def push(self):
        payload = self._data_serial()
        resp = str()
        try:
            resp = requests.post(self._agt_api, data=payload)
        except Exception as e:
            logger.error('An Error occured due to {}'.format(e))

        return resp.text
